<template>
  <div class="home-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title gradient-text">发现精彩内容</h1>
        <p class="page-subtitle">探索你感兴趣的美好生活</p>
      </div>
    </div>
    
    <!-- 内容区域 -->
    <div class="content-container">
      <!-- 加载状态 -->
      <div v-if="loading && contents.length === 0" class="loading-wrapper">
        <el-skeleton 
          v-for="i in 8" 
          :key="i" 
          animated 
          class="content-skeleton"
        >
          <template #template>
            <el-skeleton-item variant="image" style="width: 100%; height: 200px;" />
            <el-skeleton-item variant="h3" style="width: 50%" />
            <el-skeleton-item variant="text" style="width: 80%" />
          </template>
        </el-skeleton>
      </div>
      
      <!-- 内容瀑布流 -->
      <div v-else class="waterfall-container">
        <div 
          v-for="content in contents" 
          :key="content.id" 
          class="content-card xhs-card fade-in"
          @click="goToDetail(content.id)"
        >
          <!-- 内容封面 -->
          <div class="card-cover">
            <img 
              v-if="content.fileUrl" 
              :src="content.fileUrl" 
              :alt="content.title"
              class="cover-image"
              @error="handleImageError"
            />
            <div v-else class="cover-placeholder">
              <el-icon><Document /></el-icon>
            </div>
            
            <!-- 悬浮操作按钮 -->
            <div class="card-actions">
              <div class="action-item" @click.stop="toggleLike(content)">
                <el-icon :class="{ 'liked': content.isLiked }">
                  <StarFilled v-if="content.isLiked" />
                  <StarFilled v-else />
                </el-icon>
                <span>{{ content.likeCount || 0 }}</span>
              </div>
              <div class="action-item">
                <el-icon><ChatLineRound /></el-icon>
                <span>{{ content.commentCount || 0 }}</span>
              </div>
            </div>
          </div>
          
          <!-- 内容信息 -->
          <div class="card-content">
            <h3 class="content-title">{{ content.title }}</h3>
            <p class="content-description">{{ content.description }}</p>
            
            <!-- 标签 -->
            <div v-if="content.tags" class="content-tags">
              <span 
                v-for="tag in content.tags.split(',')" 
                :key="tag" 
                class="xhs-tag"
              >
                {{ tag.trim() }}
              </span>
            </div>
            
            <!-- 作者信息 -->
            <div class="author-info">
              <el-avatar :size="24" class="author-avatar">
                <el-icon><User /></el-icon>
              </el-avatar>
              <span class="author-name">{{ content.authorName || '匿名用户' }}</span>
              <span class="publish-time">{{ formatTime(content.createdAt) }}</span>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 加载更多 -->
      <div v-if="hasMore" class="load-more">
        <el-button 
          :loading="loading" 
          @click="loadMore"
          class="load-more-btn"
        >
          {{ loading ? '加载中...' : '加载更多' }}
        </el-button>
      </div>
      
      <!-- 没有更多内容 -->
      <div v-else-if="contents.length > 0" class="no-more">
        <p>没有更多内容了</p>
      </div>
      
      <!-- 空状态 -->
      <div v-else-if="!loading" class="empty-state">
        <el-empty description="暂无内容">
          <el-button type="primary" @click="$router.push('/create')">
            发布第一个内容
          </el-button>
        </el-empty>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { getRecommendedContents, toggleLike as toggleLikeApi } from '@/api/content'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import 'dayjs/locale/zh-cn'
import { 
  Document, 
  StarFilled, 
  ChatLineRound, 
  User 
} from '@element-plus/icons-vue'

const router = useRouter()

const contents = ref([])
const loading = ref(false)
const hasMore = ref(true)
const currentPage = ref(0)
const pageSize = 12

// 配置dayjs
dayjs.extend(relativeTime)
dayjs.locale('zh-cn')

// 加载推荐内容
const loadContents = async (page = 0) => {
  if (loading.value) return
  
  loading.value = true
  try {
    const res = await getRecommendedContents({
      page,
      size: pageSize
    })
    
    if (page === 0) {
      contents.value = res.data.content || []
    } else {
      contents.value.push(...(res.data.content || []))
    }
    
    hasMore.value = res.data.content && res.data.content.length === pageSize
  } catch (error) {
    console.error('加载内容失败:', error)
    ElMessage.error('加载内容失败')
  } finally {
    loading.value = false
  }
}

// 加载更多
const loadMore = () => {
  currentPage.value++
  loadContents(currentPage.value)
}

// 跳转到详情页
const goToDetail = (id) => {
  router.push(`/content/${id}`)
}

// 点赞/取消点赞
const toggleLike = async (content) => {
  try {
    await toggleLikeApi(content.id)
    content.isLiked = !content.isLiked
    content.likeCount = content.isLiked 
      ? (content.likeCount || 0) + 1 
      : Math.max((content.likeCount || 1) - 1, 0)
    
    ElMessage.success(content.isLiked ? '点赞成功' : '取消点赞')
  } catch (error) {
    console.error('点赞操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 处理图片加载错误
const handleImageError = (event) => {
  event.target.style.display = 'none'
  const placeholder = event.target.parentNode.querySelector('.cover-placeholder')
  if (placeholder) {
    placeholder.style.display = 'flex'
  }
}

// 格式化时间
const formatTime = (time) => {
  return dayjs(time).fromNow()
}

onMounted(() => {
  loadContents()
})
</script>

<style scoped lang="scss">
.home-page {
  min-height: 100vh;
  background-color: $bg-light;
}

.page-header {
  background: linear-gradient(135deg, $bg-white 0%, $secondary-color 100%);
  padding: $spacing-xl 0;
  text-align: center;
  
  .header-content {
    max-width: 1200px;
    margin: 0 auto;
    
    .page-title {
      font-size: $font-size-xxl * 1.2;
      margin-bottom: $spacing-sm;
    }
    
    .page-subtitle {
      color: $text-secondary;
      font-size: $font-size-lg;
    }
  }
}

.content-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: $spacing-lg;
}

.loading-wrapper {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  grid-gap: $spacing-md;
  
  .content-skeleton {
    background: $bg-white;
    border-radius: $border-radius-large;
    padding: $spacing-md;
  }
}

.waterfall-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  grid-gap: $spacing-md;
  
  .content-card {
    cursor: pointer;
    transition: all 0.3s ease;
    background: $bg-white;
    
    &:hover {
      transform: translateY(-4px);
      box-shadow: $shadow-medium;
      
      .card-actions {
        opacity: 1;
      }
    }
    
    .card-cover {
      position: relative;
      width: 100%;
      height: 200px;
      overflow: hidden;
      border-radius: $border-radius-large $border-radius-large 0 0;
      
      .cover-image {
        width: 100%;
        height: 100%;
        object-fit: cover;
        transition: transform 0.3s ease;
        
        &:hover {
          transform: scale(1.05);
        }
      }
      
      .cover-placeholder {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        background: $bg-light;
        color: $text-light;
        
        .el-icon {
          font-size: $spacing-xxl;
        }
      }
      
      .card-actions {
        position: absolute;
        top: $spacing-sm;
        right: $spacing-sm;
        display: flex;
        flex-direction: column;
        gap: $spacing-sm;
        opacity: 0;
        transition: opacity 0.3s ease;
        
        .action-item {
          display: flex;
          align-items: center;
          gap: $spacing-xs;
          background: rgba(255, 255, 255, 0.9);
          backdrop-filter: blur(10px);
          padding: $spacing-xs $spacing-sm;
          border-radius: $border-radius-large;
          font-size: $font-size-xs;
          color: $text-secondary;
          
          .el-icon {
            font-size: $font-size-sm;
            
            &.liked {
              color: $primary-color;
            }
          }
          
          &:hover {
            background: $bg-white;
          }
        }
      }
    }
    
    .card-content {
      padding: $spacing-md;
      
      .content-title {
        font-size: $font-size-md;
        font-weight: 600;
        color: $text-primary;
        margin-bottom: $spacing-sm;
        line-height: 1.4;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
      }
      
      .content-description {
        font-size: $font-size-sm;
        color: $text-secondary;
        margin-bottom: $spacing-sm;
        line-height: 1.5;
        display: -webkit-box;
        -webkit-line-clamp: 3;
        -webkit-box-orient: vertical;
        overflow: hidden;
      }
      
      .content-tags {
        margin-bottom: $spacing-sm;
        
        .xhs-tag {
          margin-right: $spacing-xs;
          margin-bottom: $spacing-xs;
        }
      }
      
      .author-info {
        display: flex;
        align-items: center;
        gap: $spacing-sm;
        font-size: $font-size-xs;
        color: $text-light;
        
        .author-avatar {
          border: 1px solid $border-light;
        }
        
        .author-name {
          font-weight: 500;
          color: $text-secondary;
        }
        
        .publish-time {
          margin-left: auto;
        }
      }
    }
  }
}

.load-more {
  text-align: center;
  margin-top: $spacing-xl;
  
  .load-more-btn {
    border-radius: $border-radius-large;
  }
}

.no-more {
  text-align: center;
  margin-top: $spacing-xl;
  color: $text-light;
}

.empty-state {
  margin-top: $spacing-xxl;
}

// 响应式设计
@media (max-width: $breakpoint-md) {
  .waterfall-container {
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    grid-gap: $spacing-sm;
  }
  
  .content-container {
    padding: $spacing-md;
  }
}

@media (max-width: $breakpoint-sm) {
  .page-header {
    padding: $spacing-lg 0;
    
    .page-title {
      font-size: $font-size-xl;
    }
    
    .page-subtitle {
      font-size: $font-size-md;
    }
  }
  
  .waterfall-container {
    grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
  }
  
  .content-container {
    padding: $spacing-sm;
  }
}
</style> 